//
//  BVDiscountViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/14.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//  优惠卷

#import "BVDiscountViewController.h"
#import "BVConst.h"
#import "HttpTool.h"
#import "MJExtension.h"
#import "BVMyDiscount.h"
#import "BVMyDiscountCell.h"
#import "MBProgressHUD+MJ.h"
#import "MJRefresh.h"
@interface BVDiscountViewController () <UITableViewDataSource, UITableViewDelegate,DiscountDelegate>
/**
 *  创建tableview
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 *  存放所有优惠券
 */
@property (nonatomic, strong) NSMutableArray *discountArray;
// 存放选中的优惠券

//当前选中的cell
@property (nonatomic,weak) BVMyDiscountCell * selectedCell;

@property (nonatomic,assign) NSInteger page;
@end

@implementation BVDiscountViewController


- (NSMutableArray *)discountArray {
    if (!_discountArray) {
        _discountArray = [NSMutableArray array];
    }
    return _discountArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置导航栏
    [self setupNav];
    
    // 初始化
    self.page = 1;
    
    // 创建tableView
    [self setupTableView];
    
    // 获取我的优惠券数据
    [self loadMyDiscount];

    
}

#pragma mark -- 获取我的优惠券数据
- (void)loadMyDiscount {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getMyCouponList", Path];

    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults dictionaryForKey:@"USERINFO"];
    NSString *user_id = userinfo[@"id"];
    if (user_id != nil) {
        params[@"user_id"] = user_id;
        params[@"page"] = @(self.page);
        
        SHOWLOADING
        [HttpTool get:url params:params success:^(id responseObj) {
            
            HIDELOADING
            if (self.page == 1) {
                [self.discountArray removeAllObjects];
            }
            if ([responseObj[@"code"] isEqualToString:@"1"]) {
                
                NSArray *array = [BVMyDiscount objectArrayWithKeyValuesArray:responseObj[@"data"]];
                
                for (NSInteger i = 0; i < array.count; i++) {
                    BVMyDiscount *discount = array[i];
                    
                    if ([discount.coupon_expired isEqualToString:@"0"] && [discount.status isEqualToString:@"0"]) {
                        // 优惠券没有过期,没有被使用
                        if(discount.condition.floatValue <= self.goodsMoney)
                            discount.isAvailable = YES;
                        [self.discountArray addObject:array[i]];
                    }
                }
                
                // 刷新tableView
                [self.tableView reloadData];
                [self.tableView headerEndRefreshing];
                [self.tableView footerEndRefreshing];
            }
            if(self.discountArray.count == 0){
                ERROR(@"没有可用抵价券");
            }else if(self.page != 1){
                ERROR(@"没有更多抵价券了");
            }
        } failure:^(NSError *error) {
            NETWORKINGERROR
        }];
    } else {
    }
}

#pragma mark -- 创建tableView
- (void)setupTableView {
    self.tableView  = [[UITableView alloc] init];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.frame  = CGRectMake(0, 64, BVScreenW, BVScreenH - 64);
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight  = 160;
    self.tableView.delegate  = self;
    self.tableView.dataSource  = self;
    [self.view addSubview:self.tableView];


    //上啦加载更多
    [self.tableView addFooterWithTarget:self action:@selector(loadMyDiscount)];

    //下拉刷新
    __weak  typeof(self) ws        = self;
    [self.tableView addHeaderWithCallback:^{
        ws.page = 1;
        [ws loadMyDiscount];
    }];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.discountArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建cell
    BVMyDiscountCell *cell = [BVMyDiscountCell cellWithTableView:tableView];

    BVMyDiscount *myDiscount = self.discountArray[indexPath.section];

    cell.showChooseBtn  = YES;
    // 传递数据模型
    cell.myDiscount  = myDiscount;

    cell.delegate  = self;

    cell.selectionStyle  = UITableViewCellSelectionStyleNone;

    return cell;
}





#pragma mark  DiscountCellDelegate
- (void)discountCell:(BVMyDiscountCell *)cell didSelectedDsicont:(BVMyDiscount *)discount{


    self.selectedCell.chooseBtn.selected = NO;
    
    if (self.selectedCell == cell) {
        self.selectedCell = nil;
    }else{
        self.selectedCell = cell;
    }

    self.selectedCell.chooseBtn.selected = YES;
}
// 确定选择的优惠券
- (void)refirmButtonColick {
    
    if (!self.selectedCell) {
        ERROR(@"您还没有选择优惠券");
    } else {
        
        NSIndexPath * indexPath = [self.tableView indexPathForCell:self.selectedCell];
        if ([self.delegate respondsToSelector:@selector(discountViewController:myDiscount:)]) {
            [self.delegate discountViewController:self myDiscount:self.discountArray[indexPath.section]];
            ROOTNAVPOP
        }
    }
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.title = @"选择优惠券";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];

    // 确定
    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(refirmButtonColick)];
}

#pragma mark -- 返回
- (void)backClick {
    
    BVMyDiscount * myDiscount = nil;
    if (self.selectedCell) {
        NSIndexPath * indexPath = [self.tableView indexPathForCell:self.selectedCell];
        myDiscount = self.discountArray[indexPath.section];
    }
    if ([self.delegate respondsToSelector:@selector(discountViewController:myDiscount:)]) {
        [self.delegate discountViewController:self myDiscount:myDiscount];
        ROOTNAVPOP
    } else {
        ROOTNAVPOP
    }
}
@end
